<template>
  <div class="online-monitor">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in statsData" :key="stat.title">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="24">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 在线用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>在线用户列表</span>
          <div class="header-actions">
            <el-button :icon="Refresh" @click="refreshData">刷新</el-button>
            <el-button type="danger" :icon="Delete" @click="handleBatchKickout">批量踢出</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickName" label="昵称" width="120" />
        <el-table-column prop="deptName" label="部门" width="120" />
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="location" label="登录地点" width="150" />
        <el-table-column prop="browser" label="浏览器" width="120" />
        <el-table-column prop="os" label="操作系统" width="120" />
        <el-table-column prop="loginTime" label="登录时间" width="160" />
        <el-table-column prop="lastAccessTime" label="最后访问" width="160" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '在线' ? 'success' : 'warning'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" size="small" :icon="SwitchButton" @click="handleKickout(row)">
              踢出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Delete, SwitchButton } from '@element-plus/icons-vue'
import type { OnlineUser } from '@/types/monitor'

// 统计数据
const statsData = reactive([
  {
    title: '在线用户',
    value: '89',
    icon: 'User',
    color: '#409eff'
  },
  {
    title: '今日登录',
    value: '1,234',
    icon: 'Monitor',
    color: '#67c23a'
  },
  {
    title: '平均在线时长',
    value: '2.5h',
    icon: 'Clock',
    color: '#e6a23c'
  },
  {
    title: '异常用户',
    value: '3',
    icon: 'Warning',
    color: '#f56c6c'
  }
])

// 表格数据
const tableData = ref<OnlineUser[]>([])
const loading = ref(false)
const selectedRows = ref<OnlineUser[]>([])

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 定时器
let refreshTimer: number | null = null

// 获取在线用户列表
const getOnlineUsers = async () => {
  try {
    loading.value = true
    // 模拟数据
    tableData.value = [
      {
        userId: 1,
        userName: 'admin',
        nickName: '管理员',
        deptName: '技术部',
        ipAddress: '192.168.1.100',
        location: '北京市',
        browser: 'Chrome 120.0',
        os: 'Windows 10',
        loginTime: '2024-01-27 10:30:00',
        lastAccessTime: '2024-01-27 11:45:00',
        status: '在线'
      },
      {
        userId: 2,
        userName: 'user001',
        nickName: '用户001',
        deptName: '运营部',
        ipAddress: '192.168.1.101',
        location: '上海市',
        browser: 'Firefox 121.0',
        os: 'macOS 14.0',
        loginTime: '2024-01-27 09:15:00',
        lastAccessTime: '2024-01-27 11:30:00',
        status: '在线'
      },
      {
        userId: 3,
        userName: 'user002',
        nickName: '用户002',
        deptName: '市场部',
        ipAddress: '192.168.1.102',
        location: '广州市',
        browser: 'Safari 17.0',
        os: 'macOS 14.0',
        loginTime: '2024-01-27 08:45:00',
        lastAccessTime: '2024-01-27 10:20:00',
        status: '离线'
      }
    ]
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取在线用户列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getOnlineUsers()
  ElMessage.success('数据已刷新')
}

// 踢出用户
const handleKickout = async (row: OnlineUser) => {
  try {
    await ElMessageBox.confirm(`确定要踢出用户 ${row.userName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟踢出操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('用户已踢出')
    getOnlineUsers()
  } catch (error) {
    // 用户取消
  }
}

// 批量踢出
const handleBatchKickout = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要踢出的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要踢出选中的 ${selectedRows.value.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟批量踢出操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('用户已批量踢出')
    getOnlineUsers()
  } catch (error) {
    // 用户取消
  }
}

// 选择变化
const handleSelectionChange = (selection: OnlineUser[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getOnlineUsers()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  getOnlineUsers()
}

// 启动定时刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    getOnlineUsers()
  }, 30000) // 30秒刷新一次
}

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(() => {
  getOnlineUsers()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style lang="scss" scoped>
.online-monitor {
  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }

  .stat-info {
    flex: 1;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 4px;
  }

  .stat-title {
    font-size: 14px;
    color: #909399;
  }

  .table-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 500;
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .online-monitor {
    .stats-row {
      .el-col {
        margin-bottom: 16px;
      }
    }
    
    .card-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
    
    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
}
</style>
